<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/15
 * Time: 18:58
 */

namespace app\common\mysic\order;


use app\common\mysic\MysicBase;
use think\Model;
use app\common\model\divide\Service;
use app\common\model\Order;

use think\Exception;


class AgentDividendOrderOp extends MysicBase implements OrderOpInterface
{
    /**
     * @var Model
     */
    protected $model;
    protected $order;
    protected $agents;
    protected $issue;
    protected $agentsAmount = 0;

    public function setModel(Model $model)
    {
        if(!($model instanceof Service) || empty($model)) {
            throw new Exception('设置的代理商分账订单模型不合法');
        }
        $this->model = $model;
        return $this;
    }

    public function getModel()
    {
        return $this->model;
    }

    public function setOrder(Model $order)
    {
        if(!($order instanceof Order) || empty($order)) {
            throw new Exception('设置的用户订单模型模型不合法');
        }
       $this->order = $order;
       return $this;
    }

    public function getOrder()
    {
        return $this->order;
    }

    public function setAgents(Array $agents)
    {
        if(empty($agents)) {
            throw new Exception('设置的代理集合为空');
        }
        $this->agents = $agents;
        return $this;
    }

    public function getAgents()
    {
        return $this->agents;
    }

    public function setIssue(int $issue)
    {
        if($issue < 1 ) {

            throw new Exception('代理商分账订单期号设置错误');
        }
        $this->issue = $issue;
        return $this;
    }

    public function getIssue()
    {
        return $this->issue;
    }

    public function getAgentsAmount()
    {
        return $this->agentsAmount;
    }

    public function create()
    {
        if(empty($this->agents)) {
            throw new Exception('待分账的代理账号为空');
        }
        $insertData = $log = [];
        $agentRate = [];

        foreach($this->agents as $key => $agent) {
            $data = [
                'name' => $agent['company_name'] ?? $agent['real_name'],
                'agent_id' => $agent['agent_id'],
                'amount' =>  bcmul(
                    bcdiv(strval($agent['service_charge']),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                ),

                'abonus' => bcmul(strval($this->order->pay_price),'0.01',2),
                'order_no' => $this->order->order_no,
                'payment' => $this->order->pay_price,
                'transaction_id' => $this->order->transaction_id,
                'wxapp_id' => $this->order->wxapp_id,
                'status' => 0,
                'create_time' => time(),
                'periods_num' => $this->issue
            ];

            $agent['type'] == 0 && $data['type'] = 1;
            $agent['type'] == 1 && $data['type'] = 2;
            $agent['type'] == 2 && $data['type'] = 3;
            $agentRate[] = $agent['service_charge'];
            $insertData[] = $data;
            $log[] = [
                'name' => $data['name'],
                'agent_id' => $data['agent_id'],
                'order_no' => $data['order_no'],
                'bonus' => $data['abonus']
            ];
        }

        switch(count($insertData)){
            case 1:
                $insertData[0]['amount'] = bcmul(
                    bcdiv(strval($agentRate[0]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $agentsAmount = $insertData[0]['amount'];
                break;
            case 2:
                $insertData[0]['amount'] = bcmul(
                    bcdiv(strval($agentRate[0] - $agentRate[1]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $insertData[1]['amount'] = bcmul(
                    bcdiv(strval($agentRate[1]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $agentsAmount = bcadd($insertData[0]['amount'], $insertData[1]['amount'], 4);
                break;
            case 3:
                $insertData[0]['amount'] = bcmul(
                    bcdiv(strval($agentRate[0] - $agentRate[1]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $insertData[1]['amount'] = bcmul(
                    bcdiv(strval($agentRate[1] - $agentRate[2]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $insertData[2]['amount'] = bcmul(
                    bcdiv(strval($agentRate[2]),'100',2),
                    bcdiv($this->order->pay_price, '100', 2),
                    4
                );
                $agentsAmount = bcadd(bcadd($insertData[0]['amount'], $insertData[1]['amount'], 4), $insertData[2]['amount'], 4);
                break;
            default:
                $agentsAmount = 0;
        }
        $this->agentsAmount = $agentsAmount;
        $this->log->info(json_encode($log), '各级代理商的分账订单数据');
        $this->log->info(json_encode($insertData), '各级代理商数据');
        return $this->model->insertAll($insertData);
    }

    public function failure($msg)
    {
        $this->update(2, $msg);
    }

    public function success()
    {
        $this->update(1, '分账成功');
    }

    protected function update($status, $failReason)
    {
        $updateTime = time();
        $orders = $this->model->where('order_no', $this->order->order_no)->select();
        foreach($orders as $order) {
            $updateList[] = [
                'id' => $order->id,
                'status' => $status,
                'fail_reason' => $failReason,
                'update_time' => $updateTime
            ];
        }
        $this->model->saveAll($updateList);
    }
}